package com.fanjia.crm.web.controller;

import com.fanjia.crm.model.CURDResult;
import com.fanjia.crm.model.PageResult;
import com.fanjia.crm.model.Role;
import com.fanjia.crm.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by FanJia on 2020/9/21 14:40
 */
@Controller
@RequestMapping(value = "/role")
public class RoleController {

    @Autowired
    IRoleService roleService;

    @RequestMapping("/list")
    public String list(){
        return "/role/list";
    }

    @RequestMapping("/add")
    public String add(){
        return "/role/add";
    }

    @RequestMapping("/edit")
    public String edit(Model model,Integer roleId){
        Role role = roleService.findByRoleId(roleId);
        model.addAttribute("role",role);
        model.addAttribute("ids",roleService.findPermissionIdsByRoleId(roleId));
        return "/role/edit";
    }

    @RequestMapping("/save")
    @ResponseBody
    /**
     * id  为编辑传过来的id
     * ids 为保存传
     */
    public CURDResult save(Role role,String[] ids){
        for (int i = 0; i < ids.length; i++) {
            System.out.println(ids[i]);
        }
        System.out.println(role);
        System.out.println(ids);
        CURDResult result = new CURDResult();
        try {
            roleService.insert(role,ids);
        }catch (Exception e){
            result.setSuccess(0);
        }
        return result;



    }

    @RequestMapping("/listjson")
    @ResponseBody
    public PageResult<Role> listJson(Role role){
        PageResult<Role> result = new PageResult<>();
        result.setData(roleService.findAllRoles());
        return result;

    }



}
